<template>
  <div id="new-account">
    <section class="items">
      <grey-header :title="account ? '新增提现银行卡（请仔细核对）' : '设置提现银行卡（请仔细核对）'"></grey-header>
      <ul>
        <li class="public-form-li">
          <label class="min" for="name">账户名：</label>
          <input
            :class="{'disabled': JSON.stringify(account) !== '{}'}"
            type="text"
            id="name"
            name="账户名"
            :disabled="JSON.stringify(account) !== '{}'"
            v-model="accountName"
            v-validate="'required|userName'">
          <span v-show="VeeErrors.has('账户名')">{{ VeeErrors.first('账户名') }}</span>
        </li>
        <li class="public-form-li li-click">
          <label class="min">开户行：</label>
          <input
            type="button"
            :value="accountBank"
            @click="togglePopup">
          <button
            class="type-btn"
            @click="togglePopup">
          </button>
        </li>
        <li class="public-form-li">
          <label class="min" for="accountNum">卡号：</label>
          <input
            type="text"
            id="accountNum"
            name="卡号"
            v-model="accountNum"
            @keyup="formatAccountNum($event)"
            v-validate="'required|bankNum|bankLength'">
          <span v-show="VeeErrors.has('卡号')">{{ VeeErrors.first('卡号') }}</span>
        </li>
        <li class="public-form-li">
          <label class="min" for="IDNumber">身份证：</label>
          <input
            :class="{'disabled': JSON.stringify(account) !== '{}'}"
            type="text"
            id="IDNumber"
            name="身份证号"
            :disabled="JSON.stringify(account) !== '{}'"
            v-model="IDNumber"
            v-validate="'required|idNum'">
          <span v-show="VeeErrors.has('身份证号')">{{ VeeErrors.first('身份证号') }}</span>
        </li>
      </ul>
    </section>
    <div class="public-btn-box">
      <button
        @click="back"
        class="back">返回</button>
      <button
        class="submit"
        @click="submitAccount"
        :disabled="submitAccountDisabled">提交</button>
    </div>

    <popup
      v-model="popupShow"
      position="right"
      class="popup">
      <article>
        <section
          v-for="(value, key, index) in bankList"
          :key="index">
          <grey-header :title="key"></grey-header>
          <ul>
            <li
              v-for="(subItem, subIndex) in value"
              :key="subIndex"
              @click="chooseBank(subItem.name, subItem.code)">
              {{ subItem.name }}
            </li>
          </ul>
        </section>
      </article>
    </popup>
  </div>
</template>

<script>
  import BANK from '../../assets/scripts/BANK';
  import GreyHeader from './grey-header.vue';
  import { Popup, MessageBox } from 'mint-ui';
  export default {
    name: "new-account",
    components: {
      Popup,
      GreyHeader
    },
    data() {
      let account = this.$tool.qs.parse(localStorage.getItem('account_number'));
      return {
        popupShow: false,
        account: account,
        accountName: ((JSON.stringify(account) !== '{}') && account[0].name) || '',
        accountBank: '请选择开户行',
        accountBankCode: '',
        accountNum: '',
        IDNumber: ((JSON.stringify(account) !== '{}')  && account[0].id_number) || '',
        submitAccountDisabled: false,
        bankList: {},
        timeoutFlag: ''
      }
    },
    methods: {

      // 确定修改提现账号form-account

      submitAccount() {
        this.$validator.validateAll().then((result) => {

          if (!this.accountBankCode) {
            return MessageBox.alert('请选择开户行')
          }

          // 1 - form 验证通过

          if (result) {

            // 格式化 - 还原银行卡号

            this.accountNum = this.accountNum.replace(/\s*/g,'');

            //  提交更改

            this.$http.post({
              api: this.$api.USER_SET,
              params: {
                user_id: localStorage.getItem('id'),
                type: 5,
                data: [
                  {
                    name: this.accountName,
                    bank: this.accountBankCode,
                    number: this.accountNum,
                    id_number: this.IDNumber,
                    status: 1
                  }
                ]
              },
              success: (res) => {

                // 使用localStorage存储提现账号信息

                localStorage.setItem('account_number', this.$tool.qs.stringify(res.data.data.account_number));

                MessageBox.alert('银行卡添加成功').then(action => {
                  if (this.$route.query.redirect) {
                    this.$router.push(this.$route.query.redirect);
                  } else {
                    this.$router.go(-1);
                  }
                })
              }
            });
          } else {

            // 2 - form 验证不通过

            this.$tool.whenToast(
              () => {
                // 暂时禁用确定按钮

                this.submitAccountDisabled = true;
              },
              {
                message: '请完善账户信息',
                position: 'bottom',
                className: 'public-topZ-toast',
                duration: -1
              },
              () => {

                // 恢复确定按钮

                this.submitAccountDisabled = false;
              },2000
            );
          }
        });
      },

      togglePopup() {
        this.popupShow = !this.popupShow;
      },

      chooseBank(bank, code) {
        this.accountBank = bank;
        this.accountBankCode = code;
        this.togglePopup();
      },

      formatAccountNum(e) {
        if (e.key === 'Backspace' || e.key === 'Delete') {
          clearTimeout(this.timeoutFlag);
          this.accountNum = this.accountNum.replace(/\s*$/,'');
        } else {
          clearTimeout(this.timeoutFlag);
          this.timeoutFlag = setTimeout(() => {
            this.accountNum = this.accountNum.replace(/\s*/g,'').replace(/(.{4})/g,'$1 ');
          });
        }
      },

      back() {
        this.$router.go(-1);
      }
    },
    created() {
      this.bankList = BANK.indexList;
    }
  }
</script>

<style scoped lang="scss">


  #new-account {

    background: $grey;

    >.items {
      margin-bottom: 2.3rem;

      $padding: 1.8rem;

      >header {
        height: 3rem;
        line-height: 3rem;
        padding-left: $padding;
        font-size: 1.2rem;
        color: #999;
      }

      >ul {
        padding: 0 1rem 0;
        background: $white;

        >li:last-of-type {
          border-bottom: 1px solid #eee;
        }
      }
    }

    >.popup {
      width: $size-as-parent;
      height: $size-as-parent;

      >article {
        height: 100%;
        overflow-y: scroll;

        >section {
          background: #f5f5f5;

          >ul {
            background: $white;

            >li {

              $li-height: 3.5rem;

              height: $li-height;
              line-height: $li-height;
              font-size: 1.2rem;
              color: #333;
              padding-left: 1.2rem;
              border-bottom: 1px solid #f5f5f5;
            }
          }
        }
      }
    }
  }
</style>
